package com.wzy.common.base.Youdao;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzy.common.base.util.JacksonUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/3/17 14:53
 * 4
 */
public class TranslationUtil {
    // 日志
    private static Logger logger = LoggerFactory.getLogger(TranslationUtil.class);

    // 创建okhttp3实例
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
    // 有道翻译API接口
    private static final String YOUDAO_TRANSLATE_URL = "https://openapi.youdao.com/api";
    // key
    private static final String APP_KEY = "1b08c7b23b409d2a";
    // 密钥
    private static final String APP_SECRET = "kCpoup9tkqdudd1fPy0QI7W7VGGbodeZ";
    // code
    private static final String OK = "0";


    /**
     * 句子翻译
     * @param english 原文章
     * @return 翻译后的值
     */
    public static Map<String, String> translateSentence(String english) throws Exception {
        // 获取翻译内容
        Response response = sendTranslation(english);
        if (!checkout(response)) {
            throw new Exception();
        }
        String body = response.body().string();
        logger.info("请求内容为:"+ body);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(body);
        // 如果errorCode不为0
        String errorCode = jsonNode.get("errorCode").toString();
        if (!OK.equals(errorCode.substring(1,2))) {
            logger.error("翻译请求成功,但并未返回正确结果,错误码:"+ errorCode);
            throw new Exception();
        }
        JsonNode translationNode = jsonNode.get("translation");
        String translation = translationNode.toString();
        logger.info("翻译请求成功,原文为:" + english + ",翻译为:"+ translation);
        Map<String, String> map = new HashMap<>();
        String speakUrl = jsonNode.get("speakUrl").toString();
        List<String> translations = JacksonUtil.string2List(String.class, translation);
        speakUrl = speakUrl.replace("\"", "");
        map.put("translation", translations.get(0));
        map.put("speakUrl", speakUrl);
        return map;
    }

    /**
     * 通过有道云api将单词的音标\发音\释意 放在map中
     * @param word 单词
     * @return 音标\发音\释意放在map中返回
     * @throws Exception
     */
    public static Map<String, String> translateWord(String word) throws Exception {
        Response response = sendTranslation(word);
        if (!checkout(response)) {
            throw new Exception();
        }
        String body = Objects.requireNonNull(response.body()).string();
        logger.info("请求内容为:"+ body);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(body);
        String errorCode = jsonNode.get("errorCode").toString();
        if (!OK.equals(errorCode.substring(1,2))) {
            logger.error("翻译请求成功,但并未返回正确结果,错误码:"+ errorCode);
            throw new Exception();
        }
        if(!jsonNode.get("isWord").booleanValue()) {
            // 如果查的不是单词
            Map<String, String> map = new HashMap<>();
            //map.put("");
            return null;
        } else  {
            return isWord(jsonNode);
        }

    }

    //private static Map<String,String> isNotWord(JsonNode jsonNode) {
    //    //Map<String, String> basicMap = new HashMap<>();
    //    //basicMap.put("translation", jsonNode.get("translation").toString());
    //    //basicMap.put("speakUrl")
    //    //return null;
    //}

    private static Map<String,String> isWord(JsonNode jsonNode) {
        Map<String, String> basicMap = new HashMap<>();
        JsonNode basic = jsonNode.get("basic");
        // 单词基本意思
        String explains = basic.get("explains").toString();
        List<String> explain = JacksonUtil.string2List(String.class, explains);
        basicMap.put("explains", explain.get(0));
        // 等级
        String examType = basic.get("exam_type") == null ?  "" : basic.get("exam_type").toString();
        // 转化为List类型
        // 取第一个
        // 这里可以优化一下  把level的值定义一个枚举类
        if(examType.equals("")) {
            basicMap.put("level", examType);
        } else {
            basicMap.put("level", JacksonUtil.string2List(String.class, examType).get(0));
        }

        // 音标
        // 英式音标
        if (basic.get("uk-phonetic") == null) {
            basicMap.put("ukPhonetic", "");
        } else {
            basicMap.put("ukPhonetic", basic.get("uk-phonetic").toString().replace("\"", ""));
        }

        // 美式音标
        if (basic.get("us-phonetic") == null) {
            basicMap.put("usPhonetic", "");
        } else {
            basicMap.put("usPhonetic", basic.get("us-phonetic").toString().replace("\"", ""));
        }

        // 英式发音
        if (basic.get("uk-speech") == null) {
            basicMap.put("ukSpeech", "");
        } else {
            basicMap.put("ukSpeech", basic.get("uk-speech").toString().replace("\"", ""));
        }
        // 美式发音
        if (basic.get("us-speech") == null) {
            basicMap.put("usSpeech", "");
        } else {
            basicMap.put("usSpeech", basic.get("us-speech").toString().replace("\"", ""));
        }
        return basicMap;
    }

    private static boolean checkout(Response response) {
        if (response == null) {
            return false;
        }
        if (response.code() != 200) {
            // 抛出异常
            logger.error("翻译请求失败" + response.code());
            return false;
        }
        return true;
    }

    private static Response sendTranslation(String english) {
        // 请求体参数初始化
        // 初始化设置
        String salt = String.valueOf(System.currentTimeMillis());
        // 时间戳
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String signStr = APP_KEY + truncate(english) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);
        RequestBody requestBody = new FormBody
                .Builder()
                .add("from","auto")
                .add("to","auto")
                .add("signType", "v3")
                .add("curtime", curtime)
                .add("appKey", APP_KEY)
                .add("q", english)
                .add("salt",salt)
                .add("sign", sign).build();
        // 创建request
        Request request = new Request.Builder()
                .url(YOUDAO_TRANSLATE_URL)
                .post(requestBody)
                .build();
        try {
            return HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            logger.error("OK_HTTP发送失败");
            e.printStackTrace();
            return null;
        }
    }
    // 截断
    private static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }

    /**
     * 生成加密字段
     */
    private static String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String toTranslationVideo(String path) throws NoSuchAlgorithmException {

            //String filePath = stream.mp42wav(path);;
            String from = "en";
            String to = "zh-CHS";
            String appKey = "1b08c7b23b409d2a";
            String appSecret = "kCpoup9tkqdudd1fPy0QI7W7VGGbodeZ";
            return  StreamSpeechDemo.streamSpeech(appKey, appSecret, path, from, to);

    }


    public static void main(String[] args) throws Exception {
        System.out.println(translateWord("There"));
        //System.out.println(translateSentence("　There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.\n" +
        //        "\n" +
        //        "　　May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too."));

    }
}
